<template>
  <div class="member-edit">
    <el-row :gutter="10">
      <el-col :span="5">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>头像</span>
          </div>
          <div class="avtar-wrap">
            <div class="avtar-item">
              <p><span>人脸识别照片</span></p>
              <el-upload
                class="avatar-uploader"
                action=""
                accept=".png,.jpg,.jpeg"
                :show-file-list="false"
                ref='cvue-upload'
                :headers="accessToken"
                :on-preview="handlePictureCardPreview"
                :multiple="false"
                :http-request="uploadFile"
                :auto-upload="true"
                :file-list="fileList"
                :on-remove="handleRemove">
                <ul class="list-upload-image" v-if="faceImageFile">
                  <li>
                    <img :src="faceImageFile" class="image-item">
                    <i class="el-icon-close icon-close" @click.prevent.stop="deleteFaceImage"></i>
                  </li>
                </ul>    
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">支持png/jpg，建议尺寸200*200px，大小不超过2M</div>
              </el-upload>
              <p class="avtar-tip">规格说明</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>基础信息</span>
          </div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model.trim="ruleForm.phone" :disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="姓名" prop="userName">
                  <el-input v-model.trim="ruleForm.userName" :disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="ruleForm.gender" :disabled="disabled">
                    <el-radio :label="item.dicCode" v-for="(item, index) in genderArr" :key="index">{{ item.dicName }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>详细资料</span>
          </div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model.trim="ruleForm.idCard" :disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="紧急联系人" prop="emergencyContact">
                  <el-input v-model.trim="ruleForm.emergencyContact" :disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="紧急联系人手机号" prop="emergencyContactPhone" label-width="200px">
                  <el-input v-model.trim="ruleForm.emergencyContactPhone" :disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card class="box-card" v-if="$route.query.action == 'view'">
          <div slot="header" class="clearfix">
            <span>课程信息</span>
          </div>
          <cvue-table
            :option="tableOption"
            :data="tableData"
            ref="tbl1"
            :isShowAdd="false"
            :page="page"
            :tablePage="tablePage"
            :pageSize="page.pageSize"
            :loading="tableLoading"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            @select-change="handleSelectChange"
            :isShowPage="false">
            <template slot-scope="scope" slot="courseType">
              <span>{{ scope.row.courseType === 1 ?'私教课' : '自由练'}}</span>
            </template>
            <template slot-scope="scope" slot="signCourseState">
              <span>{{ getSignCourseState(scope.row.signCourseState) }}</span>
            </template>
            <!-- 操作按钮 -->
            <el-table-column fixed="right" slot="actionMenu" label="操作" align="center" header-align="center" width="160">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleView(scope.row)" v-hasPermission="permission.view">查看</el-button>
              </template>
            </el-table-column>
          </cvue-table>
        </el-card>
        <el-card class="box-card" v-if="$route.query.action == 'view'">
          <div slot="header" class="clearfix">
            <span>门禁信息</span>
          </div>
          <cvue-table
            :option="tableOption2"
            :data="tableData2"
            ref="tbl2"
            :isShowAdd="false"
            :page="page2"
            :tablePage="tablePage2"
            :pageSize="page2.pageSize"
            :loading="tableLoading2"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            @select-change="handleSelectChange"
            :isShowPage="false">
            <template slot-scope="scope" slot="onlineFlag">
              <span>{{ scope.row.onlineFlag == 1 ? '在线' : '离线' }}</span>
            </template>
            <template slot-scope="scope" slot="region">
              <span>{{ scope.row.region == 1 ? '私教区' : '自由区' }}</span>
            </template>
            <!-- 操作按钮 -->
            <el-table-column fixed="right" slot="actionMenu" label="操作" align="center" header-align="center" width="160">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleView1(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </cvue-table>
        </el-card>
      </el-col>
    </el-row>
    <div class="edit-footer">
      <el-button @click="confirmDialog" type="primary">保存</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import cvueTable from '@/components/cvue-table'
import {getClientHeight} from '@/util/tool'
import { validPhone, validIp, validIdCN } from '@/util/validator.js'
import BMF from 'browser-md5-file'
const bmf = new BMF()
export default {
  name: 'member-edit',
  components: {
    cvueTable
  },
  data () {
    return {
      tablePage: 1,
      tableLoading: false,
      page: {
        total: 1, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
        pageSizes: [10, 50, 100]
      },
      tableOption: {
        stripe: true,
        width: '100%',
        border: true,
        index: false,
        selected: false,
        cloumn: [
          // { prop: 'index', label: '', align: 'center', width: 58 },
          { prop: 'courseName', label: '课程名称', align: 'center', sortable: true },
          { prop: 'courseType', label: '课程类型', align: 'center', sortable: true, slotStatus: true },
          { prop: 'signCourseState', label: '课程状态', align: 'center', sortable: true, slotStatus: true },
          { prop: 'payTime', label: '购买时间', align: 'center', sortable: true },
          { prop: 'teachCoachUserName', label: '关联教练', align: 'center', sortable: true },
          { prop: 'expirationEndTime', label: '有效期至', align: 'center', sortable: true },
          // { prop: 'id', label: '上次上课', align: 'left', sortable: true },
          { prop: 'remainCount', label: '剩余课时', align: 'center', sortable: true }
        ]
      },
      tableData: [
        // { name: 'ddd', code: 'sss', order: 1, status: 1 }
      ],
      tablePage2: 1,
      tableLoading2: false,
      page2: {
        total: 1, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
        pageSizes: [10, 50, 100]
      },
      tableOption2: {
        stripe: true,
        width: '100%',
        border: true,
        index: false,
        selected: false,
        cloumn: [
          { prop: 'deviceName', label: '设备名称', align: 'center', sortable: true },
          { prop: 'region', label: '所在区域', align: 'center', sortable: true, slotStatus: true },
          { prop: 'deviceControllerAppCode', label: '归属门店', align: 'center', sortable: true },
          { prop: 'onlineFlag', label: '设备状态', align: 'center', sortable: true, slotStatus: true }
        ]
      },
      tableData2: [
        // { name: 'ddd', code: 'sss', order: 1, status: 1 }
      ],
      src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      ruleForm: {
        phone: '',
        userName: '',
        gender: 1,
        idCard: '',
        emergencyContact: '',
        emergencyContactPhone: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validPhone, trigger: 'blur' }
        ]
      },
      disabled: false,
      fileList: [],
      userId: '',
      faceImageFileId: '',
      faceImageFile: '',
      genderArr: []
    }
  },
  computed: {
    height () {
      var height = getClientHeight() - 170
      return height + 'px'
    },
    ...mapGetters(['token', 'userInfo']),
    accessToken () {
      var accessToken = {
        'Authorization': this.token
      }
      return accessToken
    }
  },
  created () {
    if (this.$route.query.action == 'edit') {
      this.getMemberDetail()
    }
    if (this.$route.query.action == 'view') {
      this.getMemberDetail()
      this.disabled = true
    }
    this.getDic().then(res => {
      // console.log(res)
      this.dict = res.data
      this.dict.forEach((item, index) => {
        if (item.dicName == 'Gender') {
          this.genderArr = item.dicValueList
        }
      })
    })
    console.log(this.userInfo)
  },
  methods: {
    deleteFaceImage () {
      this.faceImageFileId = ''
      this.faceImageFile = ''
    },
    handleView (row) {
      this.actionType = 'view'
      var item = {
        value: '/home/course-data-edit'
      }
      this.$store.commit('common/CLOSE_TAG', item)
      this.$nextTick(() => {
        this.$router.push({path: '/home/course-data-edit', query: {action: 'view', id: row.id}})
      })
      this.rowData = row
    },
    handleView1 (row) {
      this.actionType = 'view'
      var item = {
        value: '/home/ac-records'
      }
      this.$store.commit('common/CLOSE_TAG', item)
      this.$nextTick(() => {
        this.$router.push({path: '/home/ac-records', query: {action: 'view', id: row.id, memberId: this.$route.query.id, name: this.ruleForm.userName, phone: this.ruleForm.phone}})
      })
      this.rowData = row
    },
    getSignCourseState (val) {
      if (val === 0) {
        return '未支付'
      } else if (val === 1) {
        return '未开始'
      } else if (val === 2) {
        return '正常'
      } else if (val === 3) {
        return '过期'
      } else {
        return ''
      }
    },
    uploadFile (param) { 
      var fileObj = param.file
      bmf.md5(fileObj, (err, md5) => {
        console.log(err, 1)
        var formData = new FormData()
        formData.append('file', fileObj)    
        formData.append('explorerId', -1)
        formData.append('md5', md5)
        formData.append('name', fileObj.name)
        formData.append('parentId', -1)
        this.$store.dispatch('fileFun/UploadFile', formData).then(res => {
          if (res.code == '200') {
            this.faceImageFileId = res.data.fileId
            this.getPic(this.faceImageFileId).then(response => {
              this.faceImageFile = response.data
            })
          }
        })
      })
    },
    submitUpload () {
      this.$refs['cvue-upload'].submit()
    },
    handlePictureCardPreview () {},
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handleResetForm () {
      this.$refs['ruleForm'].resetFields()
    },
    getMemberDetail () {
      var params = {
        userId: this.$route.query.id
      }
      this.$store.dispatch('manage/MemberDetailGet', params).then(res => {
        console.log(res) 
        if (res.code == 200) {
          var data = res.data
          this.$set(this.ruleForm, 'phone', data.phone)
          this.$set(this.ruleForm, 'userName', data.userName)
          this.$set(this.ruleForm, 'gender', data.gender)
          this.$set(this.ruleForm, 'idCard', data.idCard)
          this.$set(this.ruleForm, 'emergencyContact', data.emergencyContact)
          this.$set(this.ruleForm, 'emergencyContactPhone', data.emergencyContactPhone)
          this.userId = data.userId
          this.faceImageFileId = data.faceImageFileId
          this.getPic(this.faceImageFileId).then(response => {
            this.faceImageFile = response.data
          })
          if (this.$route.query.action == 'view') {
            this.getSignPage(data.phone)
            this.handleList2()
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 签约列表
    getSignPage (key) {
      this.tableLoading = true
      var params = {
        'size': 10000,
        'current': 1,
        'payTimeStart': '',
        'payTimeEnd': '',
        'signCourseState': '',
        'courseType': '',
        'teachCoachUserId': '',
        'key': key,
        'ext': {},
        'orders': [
          {
            'order': 'desc',
            'sort': 'createTime'
          }
        ]
      }
      this.$store.dispatch('manage/SignPage', params).then(res => {
        // console.log(res)
        if (res.code == '200') {
          var data = res.data.records
          this.tableData = data
          this.page.total = parseInt(res.data.total)
          this.page.currentPage = this.tablePage
        }
        this.tableLoading = false
      }).catch(err => {
        console.log(err)
        this.tableLoading = false
      })
    },
    // 改变pagesize
    handleSizeChange (val) {
      this.page.pageSize = val
    },
    // 改变页码
    handleCurrentChange (val) {
      this.tablePage = val
    },
    // 表格选择
    handleSelectChange (val) {
      // console.log(val)
      var arr = []
      for (var i = 0; i < val.length; i++) {
        arr.push(val[i].id)
      }
      this.selectIds = arr
      // console.log(this.selectIds)
    },
    // 列表接口
    handleList2 () {
      this.tableLoading2 = true
      var params = {
        storeId: ''
      }
      this.$store.dispatch('manage/DeviceList', params).then(res => {
        // console.log(res)
        var data = res.data
        this.tableData2 = data
        this.tableLoading2 = false
      }).catch(err => {
        console.log(err)
        this.tableLoading2 = false
      })
    },
    getPic (fileId) {
      var paramsData = {
        fileId: fileId
      }
      return this.$store.dispatch('fileFun/GetPublicUrl', paramsData)
    },
    // 关闭弹窗
    closeDialog () {
      this.closeTagTo('/home/member')
    },
    // 确认
    confirmDialog () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          var params = {
            'userId': this.$route.query.action == 'add' ? '' : this.userId,
            'birthday': this.ruleForm.birthday,
            'emergencyContact': this.ruleForm.emergencyContact,
            'emergencyContactPhone': this.ruleForm.emergencyContactPhone,
            'faceImageFileId': this.faceImageFileId,
            'gender': this.ruleForm.gender,
            'idCard': this.ruleForm.idCard,
            'phone': this.ruleForm.phone,
            'portraitPictureFileId': this.ruleForm.portraitPictureFileId,
            'userName': this.ruleForm.userName
          }
          // console.log(params)
          this.dialogLoading = true
          var url = this.$route.query.action == 'add' ? 'manage/MemberAdd' : 'manage/MemberEdit'
          this.$store.dispatch(url, params).then(res => {
            // console.log(res)
            if (res.code == '200') {
              this.$message({
                message: res.msg,
                duration: 2000,
                type: 'success'
              })
              // this.$emit('confirmDialog')
              this.closeTagTo('/home/member')
            } else {
              this.$message({ message: res.msg, duration: 2000, type: 'error' })
            }
            this.dialogLoading = false
          }).catch(err => {
            console.log(err)
            this.dialogLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.member-edit {
  padding: 0px 0 60px !important;
  height: auto !important;
  position: relative;
  .btn-list {
    float: right;
    margin-right: 10px;
    font-size: 12px;
    color: #409EFF;
    cursor: pointer;
  }
  .el-card__header,
  .el-card__body {
    padding: 15px;
  }
  .fix-lh {
    line-height: 32px;
  }
  .el-input.is-disabled .el-input__inner {
    color: #606266;
  }
  .left{
    min-height:500px;
    background:#fff;
  }
  .left-tree{
    width: 100%;
    min-height:600px;
    overflow: auto;
  }
  .left-top{
    width: 100%;
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 16px;
    color: #333;
    background: #e2e2e2;
    font-size: 15px;
  }
  .box-card{
    margin-bottom: 10px;
  }
  .avtar-wrap{
    padding: 10px 30px 30px;
    .avtar-item{
      width: 158px;
      margin: 0 auto 50px;
      p{
        line-height: 26px;
        color: #bbb;
      }
      .avtar-img{
        width: 158px;
        height: 158px;
      }
      .avtar-tip{
        color: #555;
      }
    }
  }

  .avatar-uploader {
    .el-upload{
      display: flex;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      line-height: 148px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader-icon:hover{
      border-color: #409EFF;
    }
    .list-upload-image{
      // max-width: 800px;
      overflow: hidden;
      li{
        width: 148px;
        height: 148px;
        line-height: 148px;
        display: inline-block;
        margin: 0 5px 5px;
        border: 1px dashed #d9d9d9;
        float: left;
        position: relative;
        .image-item{
          // width: 100%;
          // height: 100%;
          max-width: 100%;
          max-height: 100%;
          vertical-align: middle;
        }
        .icon-close{
          position: absolute;
          right: 0px;
          top: 0px;
          color: red;
          font-size: 18px;
        }
      }
    }
  }
  .edit-footer{
    width: calc(100% - 248px);
    height: 60px;
    line-height: 60px;
    position: fixed;
    background: #fff;
    left: 230px;
    bottom: 0;
    padding-left: 20px;
    box-sizing: border-box;
  }
  #addressMap{
    width: 100%;
    height: 300px;
  }
  .fix-address{
    margin-bottom: 0px !important;
  }
}
</style>
